<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\goods;
use DB;
use App\Http\Requests\GoodsPostRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class HomeLoginController extends Controller
{   
    //前台详情页
   public function product($id)
   {
		//根据id查询商品信息
		// $goods = Goods::where('id',$id)->first();
   		$goods = Goods::join('cate','cate.id','=','goods.cid')
   			->select('goods.*','cate.cname as pname')
   			->find($id);

		//获取子分区
    $cates = CateController::getCatesBy(1);
    //获取最新商品  
    $news = DB::select('select id,title,pic,price from goods where status=2 order by id desc limit 3');


		//查询相关的商品
		$categoods = $goods->where('cid',$goods->cid)
			->where('id','!=',$goods->id)
			->limit(3)
			->get();
      // dd($goods);
        //解析模板
        return view('home.product.product',['goods'=>$goods,'categoods'=>$categoods,'cates'=>$cates,'news'=>$news]);
   }

   //前台导航条格式化
    public static function header()
    {
        //获取子分区
        $data = CateController::getCatesBy(1);
        //解析模板
        return view('admin.layout.header',['data' => $data]); 
    }

    //前台商品列表页面
    public function category(Request $request,$id)
    {   
      //获取分页大小 (第二个参数是默认值)
      $num = $request -> input('num',4);

      //在laravel框架中的高级where条件    闭包中的$query,代表当前数据库对象
      $goods = DB::table('goods') 
            -> where('cid',$id)
            -> where(function($query) use($request){
           //判断是否有where条件  ($request在函数内部不能使用 , 使用use($request)导入)
           if($request -> input('keywords')){
              $query -> where('title','like','%'.$request -> input('keywords').'%');
           }   
      }) -> paginate($num);
        //dd($goods);
        //解析模板,分配变量
        return view('home.category.category',['goods' => $goods,'request' => $request -> all()]);
    }


}
